package _03多态的优缺点;

/**
 * 使用多态的好处
 * 当定义一个方法的参数为一个父类对象时，此方法可以接收所有该父类的子类对象
 */
public class Demo01 {
    public static void main(String[] args) {
        Animal1 a1 = new Cat1();
        show(a1);
        //猫吃鱼
        //猫捉老鼠

        Animal1 a2 = new Dog1();
        show(a2);
        //狗吃肉
        //狗看家
    }
    public static void show(Animal1 animal1){
        //调用通用方法
        animal1.eat();

        //调用子类特有方法
        //多态不能直接调用子类特有方法，只能强制转型，从父类强制转换为子类
        if (animal1 instanceof Cat1){
            Cat1 cat1 = (Cat1) animal1;
            cat1.catchMouse();
        }

        if (animal1 instanceof Dog1){
             Dog1 dog1 = (Dog1) animal1;
             dog1.lookHome();
        }

    }

}

//父类
class Animal1{
    public void eat(){
        System.out.println("动物觅食");
    }


}
//子类
class Cat1 extends Animal1{
    @Override
    public void eat() {
        System.out.println("猫吃鱼");
    }

    public void catchMouse(){
        System.out.println("猫捉老鼠");
    }
}
class Dog1 extends Animal1{
    @Override
    public void eat() {
        System.out.println("狗吃肉");
    }

    public void lookHome(){
        System.out.println("狗看家");
    }
}
